﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Module.MultiSiteFields.Interfaces;
using umbraco.interfaces;
using System.Web.UI;
using System.Web.UI.WebControls;
using Module.MultiSiteFields.Controls.DynamicTreePicker;
using Core.Module;
using umbraco.cms.businesslogic.datatype;
using Core.Module.Interfaces.Model;
using Core.Module.Interfaces;
using Core.Module.Interfaces.Controller;
using Module.MultiSiteFields.Controllers;
namespace Module.MultiSiteFields.Controls.DynamicTreePicker
{
    public class Editor : UserControl
    {
        #region properties

        public Editor() { }
        public IDataType DataType { get; set; }
        public DynamicTreePreValue PreValue { get; set; }
        private DynamicTreeValue _value;
        public DynamicTreeValue Value
        {
            get
            {
            if (Page.IsPostBack && results != null)
            {
                this.EnsureChildControls();
                string resstr = results.Value;
                if (string.IsNullOrEmpty(resstr)) return _value;
                _value = resstr.FromJson<DynamicTreeValue>();
            }
            return _value;
        }
            set { _value = value; }
        }
        protected System.Web.UI.HtmlControls.HtmlInputHidden results;
        #endregion
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            RenderEditScript();
        }
        
        private void RenderEditScript()
        {
            string val = "{}";
            if (PreValue != null)
            {
                IStartPointsController spoints=ObjectManager.Resolve<IStartPointsController>();
                foreach (TreeStartPoint spoint in PreValue.Types)
                {
                    IModuleNode node = ObjectManager.Resolve<INodeController<IBackOffice>>().Get(Request["id"]);
                    spoints.ResolveSettings(spoint, node);                    
                }
                val = PreValue.ToJson();
            }
            System.Web.UI.HtmlControls.HtmlGenericControl script = new System.Web.UI.HtmlControls.HtmlGenericControl("script");
            script.Attributes.Add("type", "text/javascript");
            script.InnerHtml = "jQuery('#" + Parent.ClientID + "').MultiSiteDynamicTreeEditor(" + val + ");";
            this.Controls.Add(script);
        }

        protected void Repeater_Content_Load(object sender, EventArgs e)
        {
            Repeater container = sender as Repeater;
            if (container == null) return;

            container.DataSource = Value==null?null:Value.Nodes;
            container.DataBind();
        }


        
    }
}
